<template>
  <div class="list-common-table">
    <t-form
      ref="form"
      :data="formDataQueryPlan"
      :label-width="80"
      :style="{ marginBottom: '20px' }"
      colon
      @reset="onReset"
      @submit="onSubmit"
    >
      <t-row>
        <t-col :span="10">
          <t-row :gutter="[24, 24]">
            <t-col :flex="1">
              <t-form-item label="测试计划" name="id">
                <t-select-input
                  v-model="selectValue"
                  :popup-visible="popupVisible"
                  :popup-props="{ overlayInnerStyle: { padding: '6px' } }"
                  placeholder="请输入测试计划关键字"
                  allow-input
                  clearable
                  @input-change="onInputChange"
                  @popup-visible-change="onPopupVisibleChange"
                >
                  <template #panel>
                    <ul class="tdesign-demo__select-input-ul-autocomplete">
                      <li v-for="item in filteredOptions" :key="item.value" @click="() => onOptionClick(item)">
                        {{ item.label }}
                      </li>
                    </ul>
                  </template>
                  <template #suffixIcon>
                    <search-icon/>
                  </template>
                </t-select-input>
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="执行结果" name="status">
                <t-select
                  v-model="formDataQueryPlan.last_status"
                  :options="TESTPLAN_STATUS_OPTIONS"
                  class="form-item-content`"
                  placeholder="请选择执行结果"
                />
              </t-form-item>
            </t-col>
<!--            这个查询功能暂时砍掉-->
<!--            <t-col :flex="1">-->
<!--              <t-form-item-->
<!--                :rules="[{ date: { delimiters: ['/', '-', '.'] }, message: '日期格式有误' },]"-->
<!--                label="创建时间"-->
<!--                name="date">-->
<!--                <t-date-picker-->
<!--                  v-model="formDataQueryPlan.create_time"-->
<!--                  :style="{ minWidth: '160px' }"-->
<!--                  class="form-item-content"-->
<!--                  placeholder="创建时间"></t-date-picker>-->
<!--              </t-form-item>-->
<!--            </t-col>-->
            <t-col :flex="1">
              <t-form-item label="创建人" name="create_user">
                <t-select
                  v-model="formDataQueryPlan.create_user"
                  class="form-item-content`"
                  @focus="loadUserList"
                  placeholder="请选择执行人"
                  @input="handleUserSelect"
                >
                  <t-option
                    v-for="item in options2"
                    :value="item.value"
                    :label="item.label"
                    :key="item.value"
                  ></t-option>
                </t-select>
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button :style="{ marginLeft: '8px' }" theme="primary" type="submit"> 查询</t-button>
          <t-button theme="default" type="reset" variant="base"> 重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <t-row justify="space-between">
      <div class="left-operation-container">
        <!--        <t-button @click="handleCreatePlan"> 创建计划</t-button>-->
        <!--        <t-button @click="handleEditPlan"> 执行计划</t-button>-->
<!--        <t-button variant="base" theme="default" :disabled="!selectedRowKeys.length" @click="handleHostDelete"> 删除主机-->
        <t-button :disabled="!selectedRowKeys.length" theme="default" variant="base" @click="visible3 = true"> 删除计划</t-button>
        <!--        <p v-if="!!selectedRowKeys.length" class="selected-count">已选{{ selectedRowKeys.length }}项</p>-->
      </div>
      <t-space direction="vertical" style="width: 100%">
        <div v-if="selectedRowKeys.length > 0" class="selected-row-alert">
          <t-alert :message="'已选' + selectedRowKeys.length + '项'" theme="success"/>
        </div>
        <div v-else class="selected-row-alert">
          <t-alert message="已选0项" theme="success"/>
        </div>
      </t-space>

    </t-row>
    <div class="table-container">
      <t-table
        :columns="columns"
        :data="data"
        :headerAffixProps="{ offsetTop, container: getContainer }"
        :headerAffixedTop="true"
        :hover="hover"
        :loading="dataLoading"
        :pagination="pagination"
        rowKey="id"
        :selected-row-keys="selectedRowKeys"
        :verticalAlign="verticalAlign"
        @change="rehandleChange"
        @page-change="rehandlePageChange"
        @select-change="rehandleSelectChange"
      >
        <template #last_status="{ row }">
          <t-tag v-if="row.last_status === TESTPLAN_STATUS.INIT" theme="warning" variant="light">未执行</t-tag>
          <t-tag v-if="row.last_status === TESTPLAN_STATUS.FAIL" theme="danger" variant="light">失败</t-tag>
          <t-tag v-if="row.last_status === TESTPLAN_STATUS.PENDING" theme="warning" variant="light">执行中</t-tag>
          <t-tag v-if="row.last_status === TESTPLAN_STATUS.SUCCESS" theme="success" variant="light">成功</t-tag>
        </template>
        <template #cron_state="{ row }">
          <t-tag v-if="row.cron_state === CRON_STATE.DOWN" theme="warning" variant="light">关闭</t-tag>
          <t-tag v-if="row.cron_state === CRON_STATE.UP" theme="success" variant="light">开启</t-tag>
        </template>
        <template #op="slotProps">
          <a class="t-button-link" @click="handleExePlan(slotProps.row)">执行</a>
          <a class="t-button-link" @click="handleEditPlan(slotProps.row)">编辑</a>
        </template>
      </t-table>
    </div>
    <!-- 测试计划 -->
    <PlanDialog
      :formData="formDataPlan"
      :items="items"
      :title="dialogTitle"
      :visible="formVisible"
      :target-value="formDataPlan.testcase_ids"
      @cancel="handleDialogCancel"
      @submit="handleDialogSubmit"
    />
    <!-- 执行测试计划 -->
    <ExePlanDialog
      :formData="formDataExePlan"
      :items="items"
      :title="dialogTitle"
      :visible="exePlanVisible"
      @cancel="handleExeDialogCancel"
      @submit="handleExeDialogSubmit"
    />

    <!--删除确认-->
    <t-dialog
      :cancelBtn="null"
      :visible.sync="visible3"
      body="确认删除选中的测试计划吗"
      header="删除确认"
      theme="warning"
      @confirm="onConfirmDel"
    />
  </div>
</template>
<script>
import {prefix} from '@/config/global';
import PlanDialog from './PlanDialog.vue';
import ExePlanDialog from './ExePlanDialog.vue';
import {
  TESTPLAN_STATUS,
  TESTPLAN_STATUS_OPTIONS,
  CRON_STATE,
} from '@/constants';
import { SearchIcon } from 'tdesign-icons-vue';

export default {
  name: 'list-table',
  components: {
    PlanDialog,
    ExePlanDialog,
    SearchIcon,
  },
  data() {
    return {
      TESTPLAN_STATUS,
      TESTPLAN_STATUS_OPTIONS,
      CRON_STATE,
      prefix,
      selectValue: '',
      popupVisible: false,
      planOptions:[],
      options2:[],
      visible3: false,
      formDataQueryPlan: {
        id:'',
        last_status: '',
        create_user: '',
      },
      formDataPlan: {
        id: '',
        testplan_name: '',
        testcase_ids: [],
      },
      formDataExePlan:{
        id:'',
        testplan_name: '',
        chain_id:'',
        node_ip_list:[],
      },
      items: [],
      data: [],
      dataLoading: false,
      value: 'first',
      selectedRowKeys: [],
      columns: [
        {colKey: 'row-select', type: 'multiple', width: 64, fixed: 'left'},
        {
          title: 'ID',
          fixed: 'left',
          width: 50,
          align: 'left',
          ellipsis: true,
          colKey: 'id',
        },
        {
          title: '计划名称',
          width: 100,
          ellipsis: true,
          colKey: 'testplan_name',
        },
        {title: '执行结果', colKey: 'last_status', width: 100, cell: {col: 'last_status'}},
        {title: '定时任务', colKey: 'cron_state', width: 100, cell: {col: 'cron_state'}},
        {
          title: '用例数',
          width: 100,
          ellipsis: true,
          colKey: 'testcase_total',
        },
        {
          title: '执行次数',
          width: 100,
          ellipsis: true,
          colKey: 'exec_num',
        },
        {
          title: '创建人',
          width: 100,
          ellipsis: true,
          colKey: 'create_user',
        },
        {
          title: '创建时间',
          width: 100,
          ellipsis: true,
          colKey: 'create_time',
        },
        {
          title: '更新时间',
          width: 100,
          ellipsis: true,
          colKey: 'update_time',
        },

        {
          align: 'left',
          fixed: 'right',
          width: 200,
          colKey: 'op',
          title: '操作',
        },
      ],
      rowKey: 'id',
      visible: false,
      formVisible: false,
      exePlanVisible: false,
      tableLayout: 'auto',
      verticalAlign: 'top',
      bordered: true,
      hover: true,
      rowClassName: (rowKey) => `${rowKey}-class`,
      // 与pagination对齐
      pagination: {
        defaultPageSize: 20,
        total: 100,
        defaultCurrent: 1,
      },
      confirmVisible: false,
      deleteIdx: -1,
      rules: {
        name: [{required: true, message: '请输入产品名称', type: 'error'}],
      },
      dialogTitle: '',
      textareaValue: '',
    };
  },
  computed: {
    filteredOptions() {
      if (this.selectValue) {
        const keyword = this.selectValue.toLowerCase();
        return this.planOptions.filter((item) =>
          item.label.toLowerCase().includes(keyword)
        );
      }
      return this.planOptions;
    },
    confirmBody() {
      if (this.deleteIdx > -1) {
        const {name} = this.data?.[this.deleteIdx];
        return `删除后，${name}的链连接信息将被清空，且无法恢复`;
      }
      return '';
    },
    offsetTop() {
      return this.$store.state.setting.isUseTabsRouter ? 48 : 0;
    },
  },
  mounted() {
    this.dataLoading = true;
    this.$request
      .get('/api/query/testplan_list')
      .then((res) => {
        console.log("测试计划页---测试计划列表~~~~~", res.data)
        if (res.data.code === '000') {
          this.data = res.data.data;
          const ids = [...new Set(this.data.map((record) => record.id))];
          this.planOptions = ids.map((id) => {
            const testplanName = this.data.find((record) => record.id === id).testplan_name;
            return {
              label: testplanName,
              value: id,
            };
          });
          // console.log("拿到的筛选数据~~~~~~~", JSON.stringify(this.planOptions))
          // console.log("拿到测试计划列表的数据", JSON.stringify(this.data))
          this.pagination = {
            ...this.pagination,
            total: this.data.length,
          };
        }
      })
      .catch((e) => {
        console.log(e);
      })
      .finally(() => {
        this.dataLoading = false;
      });
  },
  methods: {
    getContainer() {
      return document.querySelector('.tdesign-starter-layout');
    },
    rehandlePageChange(curr, pageInfo) {
      console.log('分页变化', curr, pageInfo);
    },
    rehandleChange(changeParams, triggerAndData) {
      console.log('统一Change', changeParams, triggerAndData);
    },
    // 清空搜索框的内容
    onReset(data) {
      console.log(data);
      this.formDataQueryPlan = {
        testplan_name: '',
        create_time: '',
        last_status: '',
        create_user: ''
      };
      window.location.reload(); // 刷新页面

    },
    // 按照选择的条件进行搜索
    onSubmit({validateResult, firstError}) {
      if (validateResult === true) {
        this.dataLoading = true;

        // 构建筛选参数
        // const params = {
        //   id: this.formDataQueryPlan.id,
        //   last_status: this.formDataQueryPlan.last_status,
        //   create_user: this.formDataQueryPlan.create_user
        // };
        const params = {};

        if (this.formDataQueryPlan.id) {
          params.id = this.formDataQueryPlan.id;
        }

        if (this.formDataQueryPlan.last_status !== '' && this.formDataQueryPlan.last_status !== null) {
          params.last_status = this.formDataQueryPlan.last_status;
        }

        if (this.formDataQueryPlan.create_user) {
          params.create_user = this.formDataQueryPlan.create_user;
        }

        // 发起请求，获取筛选结果
        this.$request
          .get('/api/query/testplan_list', {params})
          .then((res) => {
            if (res.data.code === '000') {
              this.data = res.data.data;
              this.pagination = {
                ...this.pagination,
                total: this.data.length
              };
            }
            this.$message.success('提交成功');
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => {
            this.dataLoading = false;
          });
      } else {
        console.log('Errors: ', validateResult);
        this.$message.warning(firstError);
      }
    },
    loadUserList() {
      this.$request
        .get('/api/user/query/user_list')
        .then((res) => {
          console.log("用户列表~~~~~", res.data)
          if (res.data.code === '000') {
            const transformedData = res.data.data.map((item) => ({
              value: item.id,
              label: item.username,
            }));
            this.options2 = transformedData
            console.log('筛选条件中的用户列表~~~~~~~~',this.options2)
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    // 删除测试计划
    onConfirmDel() {
      if (this.selectedRowKeys.length > 0) {
        const ids = this.selectedRowKeys.map((key) => this.data[key].id);
        const params = {
          ids,
        };
        this.$request
          .post('/api/del/testplan', params)
          .then((res) => {
            this.$message.success('提交成功');
            this.visible3 = false;
            window.location.reload();
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.$message.warning('请选择要删除的测试计划');
      }
    },

    // 选择一行，拿到哪一行的内容数据
    rehandleSelectChange(value, {selectedRowData}) {
      this.selectedRowKeys = value;
      console.log("！！！！！！！！！", selectedRowData);
    },
    // 执行测试计划
    handleExePlan(row) {
      console.log("row", row)
      this.exePlanVisible = true;
      this.dialogTitle = '执行测试计划'
      this.formDataExePlan = {...row};
      console.log("执行测试计划了", this.formDataExePlan)


    },
    // 编辑的时候，拿到编辑的信息
    handleEditPlan(row) {
      this.formVisible = true;
      this.dialogTitle = '修改测试计划'
      this.formDataPlan = {...row};
      console.log("修改测试计划了", this.formDataPlan)

      // this.$nextTick(() => {
      //   this.formDataPlan = {...row};
      // });
    },


    //编辑测试计划弹窗提交
    handleDialogSubmit(formDataPlan) {
      // 处理弹窗提交事件
      // 在这里可以更新父组件的数据或执行其他逻辑
      // 更新父组件的数据
      this.formDataPlan = {...formDataPlan};
      // 关闭弹窗
      this.formVisible = false;
    },
    handleDialogCancel() {
      // 处理弹窗取消事件
      this.formVisible = false;
      // 其他逻辑
    },

    //执行测试计划弹窗提交
    handleExeDialogSubmit(formDataExePlan) {
      // 处理弹窗提交事件
      // 在这里可以更新父组件的数据或执行其他逻辑
      // 更新父组件的数据
      this.formDataExePlan = {...formDataPlan};
      // 关闭弹窗
      this.exePlanVisible = false;
    },
    handleExeDialogCancel() {
      // 处理弹窗取消事件
      this.exePlanVisible = false;
      // 其他逻辑
    },

    onConfirm() {
      this.visible = false;
    },

    //下拉菜单模糊搜索
    onOptionClick(item) {
      this.selectValue = item.label;
      this.formDataQueryPlan.id = item.value; // 更新测试计划id的值
      this.popupVisible = false;
    },
    onInputChange(keyword) {
      this.selectValue = keyword;
    },
    onPopupVisibleChange(val) {
      this.popupVisible = val;
    },
    handleUserSelect(selectedValue) {
      const selectedOption = this.options2.find(item => item.value === selectedValue);
      if (selectedOption) {
        this.formDataQueryPlan.create_user = selectedOption.label;
      }
    },

  },
};
</script>

<style lang="less" scoped>
@import '@/style/variables.less';

.selected-row-alert {
  padding: 8px;
  margin-top: 8px;
  margin-bottom: 8px;
}

.selected-row-alert .td-alert-content {
  padding: 6px;
  line-height: 1;
}

.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: 30px 32px;
  border-radius: var(--td-radius-default);
}

.form-item-content {
  width: 50%;
}

.selected-count {
  display: inline-block;
  margin-left: var(--td-comp-margin-s);
  color: var(--td-text-color-secondary);
}

.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.operation-ad-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 20px;
}

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: 8px;
  }
}

.t-button + .t-button {
  margin-left: var(--td-comp-margin-s);
}

</style>
